package com.newer.veryweather.sms;

import java.util.Date;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;

import com.newer.veryweather.db.CityDAO;
import com.newer.veryweather.db.SMSDAO;
import com.newer.veryweather.entity.City;
import com.newer.veryweather.entity.SMS;
import com.newer.veryweather.net.NetUtils;
import com.newer.veryweather.net.Weather;
/*
 * 短信广播接收器
 * 
 * 格式:我要+城市+天气 例如:我要北京天气
 */
public class SMSBroadcast extends BroadcastReceiver {
	private String phoneNum = null;
	Context context;

	public void onReceive(Context context, Intent intent) {
		this.context = context;
		// 判断是否自动回复短信
		SharedPreferences prefs = context.getSharedPreferences("weather_pref",
				Context.MODE_PRIVATE);
		boolean isSelected = prefs.getBoolean("auto_sms_share", false);
		Log.i("tag", "set:" + isSelected);
		if (isSelected == false) {
			return;// 自动回复关闭了
		}

		Log.i("tag", "天气信息请求");
		// 获取短信类容
		Bundle bundle = intent.getExtras();
		Object[] obj = (Object[]) bundle.get("pdus");
		SmsMessage[] smsMessage = new SmsMessage[obj.length];
		String mgs = "";
		for (int i = 0; i < smsMessage.length; i++) {
			smsMessage[i] = SmsMessage.createFromPdu((byte[]) (obj[i]));
			phoneNum = smsMessage[i].getDisplayOriginatingAddress();
			mgs = smsMessage[i].getDisplayMessageBody();
		}
		Log.i("tag", "电话" + phoneNum + "短信" + mgs);
		// 判断请求是否复合
		CityDAO cityDao = new CityDAO(context);
		if (mgs.startsWith("我要") && mgs.endsWith("天气")) {
			String cityName = mgs.substring(mgs.indexOf("我要") + 2,
					mgs.indexOf("天气"));
			System.out.println("cityName" + cityName);
			City city = cityDao.findCityByName(cityName);
			if (city != null) {
				new MyTask().execute(city.getCity_id());
			}
		}
		cityDao.closeDB();

	}

	private void sendSms(Weather result) {

		SmsManager manager = SmsManager.getDefault();
		PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
				new Intent(), 0);
		manager.sendTextMessage(phoneNum, null, result.toString(), null,
				pendingIntent);
		SMS sms = new SMS();
		sms.setPhone(phoneNum);
		sms.setContent(result.toString());
		sms.setDate(new Date().toLocaleString());
		SMSDAO smsDao = new SMSDAO(context);
		smsDao.OpenDataBese();
		smsDao.insertSMS(sms);
		smsDao.closeDataBese();
	}

	class MyTask extends AsyncTask<String, Void, Weather> {

		@Override
		protected Weather doInBackground(String... params) {
			Weather weather = null;
			try {
				String jsonStr = NetUtils.getXmlFromInternet(params[0]);
				weather = NetUtils.parseJson(jsonStr);

			} catch (Exception e) {
				e.printStackTrace();
			}
			return weather;
		}

		@Override
		protected void onPostExecute(Weather result) {
			if (result != null) {
				sendSms(result);
			}
			super.onPostExecute(result);

		}

	}

}
